Page({
  data: {
    subjects: []
  },

  onLoad() {
    this.loadSubjects()
  },

  // 加载课程列表
  async loadSubjects() {
    const db = wx.cloud.database()
    const { data } = await db.collection('subject').get()
    this.setData({ subjects: data })
  },

  // 添加课程
  handleAdd() {
    wx.showModal({
      title: '添加课程',
      editable: true,
      placeholderText: '请输入课程名称',
      success: async (res) => {
        if (res.confirm && res.content) {
          const db = wx.cloud.database()
          await db.collection('subject').add({
            data: {
              name: res.content,
              status: true,
              createTime: db.serverDate()
            }
          })
          this.loadSubjects()
          wx.showToast({ title: '添加成功' })
        }
      }
    })
  },

  // 修改状态
  async handleStatusChange(e) {
    const { id } = e.currentTarget.dataset
    const status = e.detail.value
    
    const db = wx.cloud.database()
    await db.collection('subject').doc(id).update({
      data: { status }
    })
    
    wx.showToast({ title: '更新成功' })
  }
}) 